package com.example.wwk.graduationpractice.Fragment;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;


import com.example.wwk.graduationpractice.Activity.LoginActivity;
import com.example.wwk.graduationpractice.Activity.SettingsActivity;
import com.example.wwk.graduationpractice.Globalutils.ActivityCollector;
import com.example.wwk.graduationpractice.Globalutils.FormatTools;
import com.example.wwk.graduationpractice.Globalutils.MyApplication;
import com.example.wwk.graduationpractice.R;
import com.example.wwk.graduationpractice.SmackUtils.GetVcardUtils;

import org.jivesoftware.smack.AbstractXMPPConnection;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    //nav head
    private TextView navHeaderName;         //该用户的名称
    private ImageView navHeaderImage;       //该用户的头像
    private NavigationView navigationView;
    //intent
    private String thisuserName;
    private int identity;
    //
    private DrawerLayout mDrawerLayout;
    private ActionBar actionBar;
    //
    private AbstractXMPPConnection connection;
    //
    private TabLayout tabLayout;
    private ViewPager viewPager;
    private List<Fragment> FragmentList;
    private String[] tabTitles = new String[]{"消息", "动态"};
    private String[] tabTitles2 = new String[]{"动态", "消息"};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_activity);
        ActivityCollector.addActivity(this);
        setTitle("");
        //toolbar
        Toolbar toolbar = (Toolbar) findViewById(R.id.psychologist_list_toolbar);
        setSupportActionBar(toolbar);
        actionBarManager(actionBar);
        //intent
        Intent intent = getIntent();
        thisuserName = intent.getStringExtra("user");
        identity = intent.getIntExtra("identity", 0);
        //侧滑栏
        mDrawerLayout = (DrawerLayout) findViewById(R.id.psychologist_list_drawer_layout);
        navigationView = (NavigationView) findViewById(R.id.psychologist_list_nav_view);
        View headerView = navigationView.getHeaderView(0);              //获取NavigationView里的控件
        navHeaderName = (TextView) headerView.findViewById(R.id.nav_header_user);
        navHeaderImage = (ImageView) headerView.findViewById(R.id.nav_header_icon_image);
//        navigationView.setCheckedItem(R.id.nav_menu_setting);      //设置默认选项（颜色改变）
        navigationView.setNavigationItemSelectedListener(new MyNavigationItemSelectedListener());
        dealNavHeader(thisuserName);        //对navHeader的头像和用户名进行处理
        //获取全局连接
        connection = MyApplication.getConnection();
        //
        initViews();
        initTabs();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ActivityCollector.removeActivity(this);
    }

    private void initViews() {
        tabLayout = (TabLayout) findViewById(R.id.tl_main);
        viewPager = (ViewPager) findViewById(R.id.vp_main);
        FragmentList = new ArrayList<>();
        if (identity == LoginActivity.USER) {
            FragmentList.add(tab_message.newInstance(thisuserName, identity));
            FragmentList.add(tab_dynamic.newInstance(thisuserName, identity));
        } else if (identity == LoginActivity.DOCTOR) {
            FragmentList.add(tab_dynamic.newInstance(thisuserName, identity));
            FragmentList.add(tab_message.newInstance(thisuserName, identity));
        }

    }

    private void initTabs() {
        viewPager.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) {//viewPager
            @Override
            public Fragment getItem(int position) {
                return FragmentList.get(position);
            }

            @Override
            public int getCount() {
                return tabTitles.length;
            }

            @Override
            public CharSequence getPageTitle(int position) {
                if (identity == LoginActivity.USER)
                    return tabTitles[position];
                return tabTitles2[position];

            }
        });

        // 跟随ViewPager的页面切换
        tabLayout.setupWithViewPager(viewPager);
        if (identity == LoginActivity.USER) {
            tabLayout.getTabAt(0).setIcon(R.drawable.selector_ico01);
            tabLayout.getTabAt(1).setIcon(R.drawable.selector_ico03);
        } else if (identity == LoginActivity.DOCTOR) {
            tabLayout.getTabAt(0).setIcon(R.drawable.selector_ico03);
            tabLayout.getTabAt(1).setIcon(R.drawable.selector_ico01);
        }


        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                int position = tab.getPosition();
                viewPager.setCurrentItem(position);
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });

    }

    private void actionBarManager(ActionBar actionbar) {
        actionbar = getSupportActionBar();
        if (actionbar != null) {
            actionbar.setDisplayHomeAsUpEnabled(true);
            actionbar.setHomeButtonEnabled(true);
            actionbar.setHomeAsUpIndicator(R.drawable.ic_menu);
        }
    }

    private void dealNavHeader(String userName) {
        navHeaderName.setText(userName);        //navHeader中的用户名
        Drawable headerImage = GetVcardUtils.getUserImage(connection, userName);
        if (headerImage != null) {
            int size = 200;
            Bitmap scaleBitmap = Bitmap.createScaledBitmap(FormatTools.getInstance().drawable2Bitmap(headerImage), size, size, true);//压缩图片
            navHeaderImage.setImageBitmap(scaleBitmap);
        } else {
            navHeaderImage.setImageResource(R.drawable.default_header);
        }
    }

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // KeyEvent.KEYCODE_BACK代表返回操作.
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            MyApplication.disConnection();        //断开连接
            finish();
        }
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:             //必须要有Android前缀否则不会触发
                mDrawerLayout.openDrawer(GravityCompat.START);
                break;

            default:
        }
        return true;
    }

    class MyNavigationItemSelectedListener implements NavigationView.OnNavigationItemSelectedListener {
        //侧滑栏监听事件
        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item) {
            switch (item.getItemId()) {
                case R.id.nav_menu_logout:
                    MyApplication.disConnection();        //断开连接
                    finish();
                    break;
                case R.id.nav_menu_setting:
                    Intent intent1 = new Intent(MainActivity.this, SettingsActivity.class);
                    intent1.putExtra("thisuserName", thisuserName);
                    startActivity(intent1);
                    break;

            }
            mDrawerLayout.closeDrawers();       //关闭抽屉
            return true;
        }
    }
}
